package net.child.chess.core;

import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import net.child.chess.pieces.Piece;
import net.child.chess.pieces.IMoves;
import net.child.chess.pieces.King;
import java.util.Random;
import net.child.chess.utils.Move;

public class PlayerPieces 
{
	public PlayerPieces()
	{
		mPieces = new ArrayList<Piece>();
		mRandom = new Random();
	}
	
	public void add(Piece piece)
	{
		if(piece.type() == Piece.Type.KING)
		{
			mKing = (King)piece;
		}
		mPieces.add(piece);
	}
	
	public void remove(Piece piece)
	{
		if(piece != null)
		{
			mPieces.remove(piece);
		}
	}
	
	public King king()
	{
		return mKing;
	}
	
	public boolean isSquareUnderAttack(IMoves iMoves, int position)
	{
		List<Integer> squares = new ArrayList<Integer>();
		Iterator<Piece> pieceIter = mPieces.iterator();
		while(pieceIter.hasNext())
		{
			squares.clear();
			Piece piece = pieceIter.next();
			piece.attacks(squares, iMoves);
			if(squares.contains(position))
			{
				return true;
			}
		}  
		return false;
	}
	
	public void reset()
	{
		mKing = null;
		mPieces.clear();
	}
	
	public Move randomMove(IMoves iMoves)
	{
		List<Move> allMoves = new ArrayList<Move>();
		List<Integer> pieceMoves = new ArrayList<Integer>();
		Iterator<Piece> pieceIter = mPieces.iterator();
		while(pieceIter.hasNext())
		{
			pieceMoves.clear();
			Piece piece = pieceIter.next();
			piece.moves(pieceMoves, iMoves);
			Iterator<Integer> pieceMovesIter = pieceMoves.iterator();
			while(pieceMovesIter.hasNext())
			{
				allMoves.add(new Move(piece.position().position(), pieceMovesIter.next()));
			}
		}
		if(allMoves.size() == 0)
		{
			return null;
		}
		int randomMove = mRandom.nextInt(allMoves.size());
		return allMoves.get(randomMove);
	}
	
	public boolean hasValidMoves(IMoves iMoves)
	{
		List<Integer> pieceMoves = new ArrayList<Integer>();
		Iterator<Piece> pieceIter = mPieces.iterator();
		while(pieceIter.hasNext())
		{
			pieceMoves.clear();
			Piece piece = pieceIter.next();
			piece.moves(pieceMoves, iMoves);
			if(pieceMoves.size() > 0)
			{
				return true;
			}
		}
		return false;
	}
	
	private King mKing;
	List<Piece> mPieces;
	Random mRandom;
}

